<template>
    <template v-if="$route.path === '/resource'">
        <el-form :inline="true" :model="queryForm" size="large" class="query">
            <el-form-item label="">
                <el-input v-model="queryForm.search" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="query">
                    <Iconfont icon="icon-search" color="white">&nbsp;查询</Iconfont>
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="$router.push(`/resource/add/-1`)">
                    <Iconfont icon="icon-add" color="white">&nbsp;新增文件夹</Iconfont>
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-upload :show-file-list="false" limit="1" :before-upload="(file) => UploadImage(file, -1)">
                    <el-button type="success">
                        <Iconfont icon="icon-line-upload" color="white">&nbsp;上传文件</Iconfont>
                    </el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <el-scrollbar max-height="calc(100vh - 200px)">
        <el-table :data="listpage.list" class="table myTable" size="large" row-key="id" v-loading="loading" 
            :row-style="{ height: '15px' }" :cell-style="{ height: '10px' }" :default-expand-all="true">
            <el-table-column label="名称" align="left" style="text-align: center;">
                <template #default="scope">
                    <el-icon color="#409eff" style="margin-right: 15px;" v-if="scope.row.isFolder == true">
                        <Folder />
                    </el-icon>
                    <span style="padding-top: 100px;">{{ scope.row.resourceName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="大小" align="left">
                <template #default="scope">
                    <span>{{ scope.row.isFolder == true ? '/' : scope.row.resourceSize / 1000 + 'KB' }}</span>
                </template>
            </el-table-column>
            <el-table-column property="updateTime" label="更新时间" align="left" />
            <el-table-column prop="" label="操作" align="left" class="myOption">
                <template #default="scope">
                    <el-tooltip effect="dark" content="打开" v-if="scope.row.isFolder !== true"
                        action="{{scope.row.httpUrl}}">
                        <el-icon :size="18" color="#409eff" style="margin-align: center; margin-right: 15px;"
                            @click="downloadFile(scope.row.httpUrl)">
                            <FullScreen />
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="添加文件夹" v-if="scope.row.isFolder === true">
                        <el-icon :size="18" color="#409eff" style="margin-right: 15px; "
                            @click="$router.push(`/resource/add/${scope.row.id}`)">
                            <DocumentAdd />
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="修改" v-if="scope.row.isFolder === true">
                        <el-icon :size="18" color="#409eff" style="margin-right: 15px; "
                            @click="$router.push(`/resource/edit/${scope.row.id}`)">
                            <Edit />
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip v-if="scope.row.isFolder == true" effect="dark" content="上传文件">
                        <el-upload :show-file-list="false" limit="1"
                            :before-upload="(file) => UploadImage(file, scope.row.id)">
                            <el-icon :size="18" color="#409eff" style="margin-right: 15px" @click="">
                                <Upload />
                            </el-icon>

                        </el-upload>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="删除">
                        <el-icon :size="18" color="#409eff" @click="$router.push(`/resource/del/${scope.row.id}`)">
                            <Delete />
                        </el-icon>
                    </el-tooltip>

                </template>
            </el-table-column>
        </el-table>
    </el-scrollbar>
    </template>
    <RouterView v-else></RouterView>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import http from "@/request/indexLoad"
import http1 from "@/request"
import { Upload, FullScreen, DocumentAdd, Edit, Delete, Folder } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import { ElMessage, type UploadFile, type UploadFiles, type UploadRawFile } from 'element-plus';
import dayjs from 'dayjs';
import type { UploadProps } from 'element-plus'


//  定义变量
const route = useRoute()
let loading = ref(false)
const userStore = useUserStore()
const queryForm = reactive({// 查询表单
    search: '',
})
const listpage = reactive({// 分页列表
    curPage: 1,
    pageSize: 100,
    total: 0,
    list: [] as any[],
})

// const file = ref()
const parentId = ref(0);

// const changeFile = (uploadFile: UploadFile) => {
//     file.value = uploadFile;
// }
const uploadForm = reactive({
    data: {
        id: '',
        parentId: -1,
        name: '',
        type: ''
    }
})

// 组件挂载完成后，执行如下方法
onMounted(() => {
    query()
})

// 如果是跳转到列表页，重新查询
watch(() => route.path, (n, o) => {
    if (n === '/resource') {
        query()
    }
})

// function isFolder(str: Date){

// }
function downloadFile(fileName: URL) {
    window.open(fileName, '_blank');
}

async function UploadImage(file: any, parentId: any) {
    loading = ref(true);
    let formData = new FormData();
    formData.append("parentId", parentId);
    formData.append("file", file);
    let { data: { code } } = await http.post("resource/upload", formData)
    if (code == 200) {
        loading = ref(false);
        ElMessage.info("上传成功");
        query()
    }
    return false;
}

// 查询
async function query() {
    const { data: { code, data } } = await http1.post('resource/listResource', {
        search: queryForm.search,
        curPage: listpage.curPage,
        pageSize: listpage.pageSize,
    })

    if (code !== 200) {
        return
    }
    let startTime = dayjs(data.startTime, 'YYYY-MM-DD HH:mm:ss').toDate()
    let list = data.list
    const treeList = []// 列表转树形列表
    const treeMap: any = {}
    const idFiled = 'id'
    const parentField = 'parentId'
    for (let i = 0; i < list.length; i++) {
        list[i]['id'] = list[i][idFiled]
        treeMap[list[i]['id']] = list[i]
    }

    for (let i = 0; i < list.length; i++) {
        if (treeMap[list[i][parentField]] && list[i]['id'] !== list[i][parentField]) {
            if (!treeMap[list[i][parentField]]['children']) {
                treeMap[list[i][parentField]]['children'] = []
            }
            treeMap[list[i][parentField]]['children'].push(list[i])
        } else {
            treeList.push(list[i])
        }
    }

    listpage.list = treeList
    listpage.total = data.total
}

// 下载模板
async function download() {
    let data = await http.post('resource/template', {}, { responseType: 'blob' })
    const blob = new Blob([data.data]);
    const aEle = document.createElement('a');
    aEle.download = '机构模板.xlsx';
    aEle.style.display = 'none';
    aEle.href = URL.createObjectURL(blob);
    aEle.click();
    URL.revokeObjectURL(aEle.href);
}

// 上传之前处理
function uploadBefore(rawFile: UploadRawFile) {
    // if (rawFile.name.indexOf('.xlsx') === -1) {
    //     ElMessage.error('只允许 xlsx 文件')
    //     return false
    // }
    // if (rawFile.size / 1024 > 512) {
    //     ElMessage.error('最大0.5兆')
    //     return false
    // }

    return true
}

// 上传成功处理
async function uploadSuccess(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) {
    // await http.post('resource/import', {fileId: response.data.fileIds})
    query()
}
const handleAvatarSuccess: UploadProps['onSuccess'] = () => {
    query()
}

</script>

<style lang="scss" scoped>
.el-tooltip__trigger{

}
.myTable {
    :deep .el-table_1_column_4 .cell{
        display: flex;
    }
    :deep .el-tooltip__trigger{
        display: inline-block;
    }
}
</style>